package com.yzcrm.erp.admin.service;

import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.jfinal.aop.Before;
import com.jfinal.config.Constants;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.yzcrm.erp.admin.entity.AdminFile;
import com.yzcrm.erp.admin.entity.AdminModalFile;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.FileUploadUtil;
import com.yzcrm.utils.R;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class AdminFileService {
//    public final static Prop prop = PropKit.use("config/yzcrm-config.txt");
    private static Prop p = PropKit.use("config/aliyun.txt");

    /**
     * @param file    文件
     * @param batchId 批次ID
     */
    public R upload(UploadFile file, String batchId, String fileType, String prefix, HttpServletRequest request) {
        if (batchId == null || "".equals(batchId)) {
            batchId = IdUtil.simpleUUID();
        }
        AdminFile adminFile = new AdminFile();
        adminFile.setBatchId(batchId);
        adminFile.setCreateTime(new Date());
        adminFile.setCreateUserId(BaseUtil.getUser().getUserId());
        adminFile.setPath(file.getFile().getAbsolutePath());
        if(ClassLoaderUtil.isPresent("com.jfinal.server.undertow.UndertowServer")){
            adminFile.setFilePath("/upload/" + prefix + "/" + file.getFileName());
        }else {
            adminFile.setFilePath(BaseUtil.getIpAddress(request)+new Constants().getBaseUploadPath()+"/"+ prefix + "/" + file.getFileName());
        }
        adminFile.setName(file.getFileName());
        if(StrUtil.isNotBlank(fileType)){
            adminFile.setFileType(fileType);
        }
        adminFile.setSize(file.getFile().length());
        return adminFile.save() ? R.ok().put("batchId", batchId).put("name",file.getFileName()).put("url", adminFile.getFilePath()).put("size",file.getFile().length()/1000+"KB").put("file_id",adminFile.getFileId()) : R.error();
    }

    public R uploadOss(UploadFile uploadFile, String batchId, String fileType, String prefix, HttpServletRequest request) {

        OSS ossClient = FileUploadUtil.ossClient;
        File file = new File(uploadFile.getUploadPath() + "/" + uploadFile.getOriginalFileName());
        String uuid = IdUtil.simpleUUID();

        new Thread(new Runnable(){
            public void run() {

                FileUploadUtil fileUpload = new FileUploadUtil();
                fileUpload.setUuid(uuid);
                fileUpload.uploadOss(ossClient, file, p.get("BACKET_NAME"), p.get("FOLDER"));

                boolean result = file.delete();
                System.out.println("删除结果" + result);
            }
        }).start();

//        Encoder encoder = new Encoder();
//        try {
//            MultimediaInfo m = encoder.getInfo(source);
//            long ls = m.getDuration();
//            int second = ls \ 1000;
//            System.out.println("此视频时长为:" + second + "秒！");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        return R.ok().put("uuid", uuid).put("name", uploadFile.getOriginalFileName());
    }

    /**
     * 获取上传进度
     * @param uuid
     * @return
     */
    public R getUploadOssProcess(String uuid) {

        String uploadInfo =  FileUploadUtil.getFileUploadProcess(uuid);
        if(ObjectUtil.isEmpty(uploadInfo)) {
            return R.ok().put("data", null);
        }

        JSONObject json = JSONObject.parseObject(uploadInfo);
        Integer total = json.getInteger("total");
        Integer count = json.getInteger("count");
        Integer code = json.getInteger("code");
        if(code == 0 || total == count) {
            // 已上传完毕或失败 获取后删除
            FileUploadUtil.removeFileUploadProcess(uuid);
        }

        return R.ok().put("data", json);
    }
    
    public R uploadModalFile(UploadFile file, String batchId, String fileType, String prefix, HttpServletRequest request,String recordId,String modalType,String modalSubType) {
        if (batchId == null || "".equals(batchId)) {
            batchId = IdUtil.simpleUUID();
        }
        AdminFile adminFile = new AdminFile();
        adminFile.setBatchId(batchId);
        adminFile.setCreateTime(new Date());
        adminFile.setCreateUserId(BaseUtil.getUser().getUserId());
        adminFile.setPath(file.getFile().getAbsolutePath());
        if(ClassLoaderUtil.isPresent("com.jfinal.server.undertow.UndertowServer")){
            adminFile.setFilePath(BaseUtil.getIpAddress(request) + prefix + "/" + file.getFileName());
        }else {
            adminFile.setFilePath(BaseUtil.getIpAddress(request)+new Constants().getBaseUploadPath()+"/"+ prefix + "/" + file.getFileName());
        }
        adminFile.setName(file.getFileName());
        if(StrUtil.isNotBlank(fileType)){
            adminFile.setFileType(fileType);
        }
        adminFile.setSize(file.getFile().length());
        Boolean flag = false;
        flag = adminFile.save();
        AdminModalFile adminModalFile = new AdminModalFile();
        if(recordId != null) {
        	adminModalFile.setRecordId(new Integer(recordId));
        	adminModalFile.setType(new Integer(modalType));
        	adminModalFile.setSubType(new Integer(modalSubType));
        	adminModalFile.setFileId(adminFile.getFileId());
        	flag = adminModalFile.save();
        }
        return flag ? R.ok().put("batchId", batchId).put("name",file.getFileName()).put("url", adminFile.getFilePath()).put("size",file.getFile().length()/1000+"KB").put("file_id",adminFile.getFileId()) : R.error();
    }

    /**
     * 通过批次ID查询
     *
     * @param batchId 批次ID
     */
    public void queryByBatchId(String batchId,Record record) {
        if (batchId == null||"".equals(batchId)) {
            record.set("img",new ArrayList<>()).set("file",new ArrayList<>());
            return;
        }
        List<AdminFile> adminFiles=AdminFile.dao.find(Db.getSql("admin.file.queryByBatchId"), batchId);

        Map<String, List<AdminFile>> collect = adminFiles.stream().collect(Collectors.groupingBy(AdminFile::getFileType));
        collect.forEach(record::set);
        if(!record.getColumns().containsKey("img")||record.get("img")==null){
            record.set("img",new ArrayList<>());
        }
        if(!record.getColumns().containsKey("file")||record.get("file")==null){
            record.set("file",new ArrayList<>());
        }

    }

    public List<AdminFile> queryByBatchId(String batchId) {
        if (batchId == null) {
            return new ArrayList<>();
        }
        return AdminFile.dao.find(Db.getSql("admin.file.queryByBatchId"), batchId);
    }
    /**
     * 通过ID查询
     *
     * @param id 文件ID
     */
    public R queryById(String id) {
        if (id == null) {
            return R.error("id参数为空");
        }
        return R.ok().put("data", AdminFile.dao.findById(id));
    }

    /**
     * 通过ID删除
     *
     * @param id 文件ID
     */
    @SuppressWarnings("all")
    @Before(Tx.class)
    public R removeById(String id) {
        if (id == null) {
            return R.error("id参数为空");
        }
        AdminFile adminFile=AdminFile.dao.findById(id);
        if(adminFile!=null){
            File file=new File(adminFile.getPath());
            if(file.exists()&&!file.isDirectory()){
                file.delete();
                adminFile.delete();
            }
        }
        return R.ok();
    }
    
    @SuppressWarnings("all")
    @Before(Tx.class)
    public R removeModalFileById(String id,String modalFileId) {
        if (id == null) {
            return R.error("id参数为空");
        }
        Boolean flag = false;
        AdminFile adminFile=AdminFile.dao.findById(id);
        if(adminFile!=null){
            File file=new File(adminFile.getPath());
            if(file.exists()&&!file.isDirectory()){
                file.delete();
                flag = adminFile.delete();
            }
        }
        AdminModalFile adminModalFile = AdminModalFile.dao.findById(modalFileId);
        flag = adminModalFile.delete();
        return flag ? R.ok() : R.error("无法删除");
    }
    /**
     * 通过批次ID删除
     *
     * @param batchId 批次ID
     */
    public void removeByBatchId(String batchId) {
        if(StrUtil.isEmpty(batchId)){
            return;
        }
        List<String> paths=Db.query(Db.getSql("admin.file.queryPathByBatchId"), batchId);

        paths.stream().map(File::new).filter(file -> file.exists() && !file.isDirectory()).forEach(File::delete);
        Db.deleteById("yzcrm_admin_file","batch_id",batchId);
    }
    public boolean renameFileById(AdminFile file){
        return Db.update("yzcrm_admin_file","file_id",file.toRecord());
    }
    
    /**
     * 通过批次ID查询
     *
     * @param recordId  模块记录ID
     * @param type  模块类型，1--合同   2-- 回款   3--线索  4--客户
     * @param subType  子模块类型
     */
    public List<AdminFile> queryModalFiles(Integer recordId,int type, int subType) {
    	if (recordId == null) {
            return new ArrayList<>();
        }
		return AdminFile.dao.find(Db.getSql("admin.file.queryModalFiles"),recordId,type,subType);
    }
}
